import copy
import hashlib
import json
import os.path
import re
import sys
from collections import OrderedDict

import gyp
from gyp import msvs_emulation, xcode_emulation
from gyp.generator.ninja import generator_default_variables, OpenOutput, GetWinLinkRuleNameSuffix, CalculateVariables
from gyp.lib import ninja_syntax


class Target(object):
  """Target represents the paths used within a single gyp target.

  Conceptually, building a single target A is a series of steps:

  1) actions/rules/copies  generates source/resources/etc.
  2) compiles              generates .o files
  3) link                  generates a binary (library/executable)
  4) bundle                merges the above in a mac bundle

  (Any of these steps can be optional.)

  From a build ordering perspective, a dependent target B could just
  depend on the last output of this series of steps.

  But some dependent commands sometimes need to reach inside the box.
  For example, when linking B it needs to get the path to the static
  library generated by A.

  This object stores those paths.  To keep things simple, member
  variables only store concrete paths to single files, while methods
  compute derived values like "the last output of the target".
  """

  def __init__(self, type_arg):
    # Gyp type ("static_library", etc.) of this target.
    self.type = type_arg
    # File representing whether any input dependencies necessary for
    # dependent actions have completed.
    self.preaction_stamp = None
    # File representing whether any input dependencies necessary for
    # dependent compiles have completed.
    self.precompile_stamp = None
    # File representing the completion of actions/rules/copies, if any.
    self.actions_stamp = None
    # Path to the output of the link step, if any.
    self.binary = None
    # Path to the file representing the completion of building the bundle,
    # if any.
    self.bundle = None
    # On Windows, incremental linking requires linking against all the .objs
    # that compose a .lib (rather than the .lib itself). That list is stored
    # here. In this case, we also need to save the compile_deps for the target,
    # so that the the target that directly depends on the .objs can also depend
    # on those.
    self.component_objs = None
    self.compile_deps = None
    # Windows only. The import .lib is the output of a build step, but
    # because dependents only link against the lib (not both the lib and the
    # dll) we keep track of the import library here.
    self.import_lib = None
    # Track if this target contains any C++ files, to decide if gcc or g++
    # should be used for linking.
    self.uses_cpp = False

  def Linkable(self):
    """Return true if this is a target that can be linked against."""
    return self.type in ('static_library', 'shared_library')

  def UsesToc(self, flavor):
    """Return true if the target should produce a restat rule based on a TOC
    file."""
    # For bundles, the .TOC should be produced for the binary, not for
    # FinalOutput(). But the naive approach would put the TOC file into the
    # bundle, so don't do this for bundles for now.
    if flavor == 'win' or self.bundle:
      return False
    return self.type in ('shared_library', 'loadable_module')

  def PreActionInput(self, flavor):
    """Return the path, if any, that should be used as a dependency of
    any dependent action step."""
    if self.UsesToc(flavor):
      return self.FinalOutput() + '.TOC'
    return self.FinalOutput() or self.preaction_stamp

  def PreCompileInput(self):
    """Return the path, if any, that should be used as a dependency of
    any dependent compile step."""
    return self.actions_stamp or self.precompile_stamp

  def FinalOutput(self):
    """Return the last output of the target, which depends on all prior
    steps."""
    return self.bundle or self.binary or self.actions_stamp


# A small discourse on paths as used within the Ninja build:
# All files we produce (both at gyp and at build time) appear in the build directory (e.g. out/Debug).
#
# Paths within a given .gyp file are always relative to the directory containing the .gyp file. Call these "gyp paths".
# This includes sources as well as the starting directory a given gyp rule/action expects to be run from.
# We call the path from the source root to the gyp file the "base directory" within the per-.gyp-file NinjaWriter code.
#
# All paths as written into the .ninja files are relative to the build directory.  Call these paths "ninja paths".
#
# We translate between these two notions of paths with two helper functions:
#
# - NinjaWriter._GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) into the equivalent ninja path.
#
# - NinjaWriter._GypPathToUniqueOutput translates a gyp path into a ninja path to write an output file; the result can be namespaced such that it is unique
#   to the input file name as well as the output target name.
class NinjaWriter(object):
  def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, spec, generator_flags, config_name, toplevel_dir):
    """
    base_dir: path from source root to directory containing this gyp file,
              by gyp semantics, all input paths are relative to this
    build_dir: path from source root to build output
    toplevel_dir: path to the toplevel directory
    """
    self.flavor = flavor
    self.spec = spec
    self.generator_flags = generator_flags
    self.xcode_settings = self.msvs_settings = None
    self.is_mac_bundle = xcode_emulation.IsMacBundle(self.flavor, spec)
    self.target_rpath = self.generator_flags.get('target_rpath', r'\$$ORIGIN/lib/')
    self.is_standalone_static_library = bool(spec.get('standalone_static_library', 0))
    self.target = Target(spec['type'])
    self.toolset = spec['toolset']
    self.name = spec['target_name']
    self.config_name = config_name
    self.config = spec['configurations'][self.config_name]
    self.hash_for_rules = hash_for_rules
    self.target_outputs = target_outputs
    self.base_dir = base_dir
    self.build_dir = build_dir
    self.ninja = ninja_syntax.Writer(output_file)
    self.toplevel_build = toplevel_build
    self.output_file_name = output_file_name
    self.archs = []
    self.arch_subninjas = []

    self.abs_build_dir = None
    if toplevel_dir is not None:
      self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir))
    self.obj_ext = '.obj' if flavor == 'win' else '.o'
    if flavor == 'win':
      # See docstring of msvs_emulation.GenerateEnvironmentFiles().
      self.win_env = {}
      for arch in ('x86', 'x64'):
        self.win_env[arch] = 'environment.' + arch

    # Relative path from build output dir to base dir.
    build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir)
    self.build_to_base = os.path.join(build_to_top, base_dir)
    # Relative path from base dir to build dir.
    base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir)
    self.base_to_build = os.path.join(base_to_top, build_dir)

  def _ExpandSpecial(self, path, product_dir=None):
    """Expand specials like $!PRODUCT_DIR in |path|.

    If |product_dir| is None, assumes the cwd is already the product
    dir.  Otherwise, |product_dir| is the relative path to the product
    dir.
    """

    PRODUCT_DIR = '$!PRODUCT_DIR'
    if PRODUCT_DIR in path:
      if product_dir:
        path = path.replace(PRODUCT_DIR, product_dir)
      else:
        path = path.replace(PRODUCT_DIR + '/', '')
        path = path.replace(PRODUCT_DIR + '\\', '')
        path = path.replace(PRODUCT_DIR, '.')

    INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR'
    if INTERMEDIATE_DIR in path:
      int_dir = self._GypPathToUniqueOutput('gen')
      # _GypPathToUniqueOutput generates a path relative to the product dir,
      # so insert product_dir in front if it is provided.
      path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir))

    CONFIGURATION_NAME = '$|CONFIGURATION_NAME'
    path = path.replace(CONFIGURATION_NAME, self.config_name)

    return path

  def _ExpandRuleVariables(self, path, root, dirname, source, ext, name):
    if self.flavor == 'win':
      path = self.msvs_settings.ConvertVSMacros(path, config=self.config_name)
    path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root)
    path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname)
    path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source)
    path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext)
    path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name)
    return path

  def _GypPathToNinja(self, path, env=None):
    """Translate a gyp path to a ninja path, optionally expanding environment
    variable references in |path| with |env|.

    See the above discourse on path conversions."""
    if env:
      if self.flavor == 'mac':
        path = gyp.xcode_emulation.ExpandEnvVars(path, env)
      elif self.flavor == 'win':
        path = gyp.msvs_emulation.ExpandMacros(path, env)
    if path.startswith('$!'):
      expanded = self._ExpandSpecial(path)
      if self.flavor == 'win':
        expanded = os.path.normpath(expanded)
      return expanded
    if '$|' in path:
      path = self._ExpandSpecial(path)
    assert '$' not in path, path
    return os.path.normpath(os.path.join(self.build_to_base, path))

  def _GypPathToUniqueOutput(self, path, qualified=True):
    """Translate a gyp path to a ninja path for writing output.

    If qualified is True, qualify the resulting filename with the name
    of the target.  This is necessary when e.g. compiling the same
    path twice for two separate output targets.

    See the above discourse on path conversions."""

    path = self._ExpandSpecial(path)
    assert not path.startswith('$'), path

    # Translate the path following this scheme:
    #   Input: foo/bar.gyp, target targ, references baz/out.o
    #   Output: obj/foo/baz/targ.out.o (if qualified)
    #           obj/foo/baz/out.o (otherwise)
    #     (and obj.host instead of obj for cross-compiles)
    #
    # Why this scheme and not some other one?
    # 1) for a given input, you can compute all derived outputs by matching
    #    its path, even if the input is brought via a gyp file with '..'.
    # 2) simple files like libraries and stamps have a simple filename.

    obj = 'obj'
    if self.toolset != 'target':
      obj += '.' + self.toolset

    path_dir, path_basename = os.path.split(path)
    assert not os.path.isabs(path_dir), ("'%s' can not be absolute path (see crbug.com/462153)." % path_dir)

    if qualified:
      path_basename = self.name + '.' + path_basename
    return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename))

  def _WriteCollapsedDependencies(self, name, targets, order_only=None):
    """Given a list of targets, return a path for a single file
    representing the result of building all the targets or None.

    Uses a stamp file if necessary."""

    assert targets == [t for t in targets if t], targets
    if len(targets) == 0:
      assert not order_only
      return None
    if len(targets) > 1 or order_only:
      stamp = self._GypPathToUniqueOutput(name + '.stamp')
      targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only)
      self.ninja.newline()
    return targets[0]

  def _SubninjaNameForArch(self, arch):
    output_file_base = os.path.splitext(self.output_file_name)[0]
    return '%s.%s.ninja' % (output_file_base, arch)

  def _WinIdlRule(self, source, prebuild, outputs):
    """Handle the implicit VS .idl rule for one source file. Fills |outputs|
    with files that are generated."""
    outdir, output, raw_vars, flags = self.msvs_settings.GetIdlBuildData(source, self.config_name)
    outdir = self._GypPathToNinja(outdir)

    def fix_path(path, rel=None):
      path = os.path.join(outdir, path)
      dirname, basename = os.path.split(source)
      root, ext = os.path.splitext(basename)
      path = self._ExpandRuleVariables(path, root, dirname, source, ext, basename)
      if rel:
        path = os.path.relpath(path, rel)
      return path

    variables = [(name, fix_path(value, outdir)) for name, value in raw_vars]
    output = [fix_path(p) for p in output]
    variables.append(('outdir', outdir))
    variables.append(('idlflags', flags))
    inpt = self._GypPathToNinja(source)
    self.ninja.build(output, 'idl', inpt, variables=variables, order_only=prebuild)
    outputs.extend(output)

  def _WriteWinIdlFiles(self, spec, prebuild):
    """Writes rules to match MSVS's implicit idl handling."""
    assert self.flavor == 'win'
    if self.msvs_settings.HasExplicitIdlRulesOrActions(spec):
      return []
    outputs = []
    for source in filter(lambda x: x.endswith('.idl'), spec['sources']):
      self._WinIdlRule(source, prebuild, outputs)
    return outputs

  def _WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends):
    """Write out the Actions, Rules, and Copies steps.  Return a path
    representing the outputs of these steps."""
    outputs = []
    if self.is_mac_bundle:
      mac_bundle_resources = spec.get('mac_bundle_resources', [])[:]
    else:
      mac_bundle_resources = []
    extra_mac_bundle_resources = []

    if 'actions' in spec:
      outputs += self._WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources)
    if 'rules' in spec:
      outputs += self._WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources)
    if 'copies' in spec:
      outputs += self._WriteCopies(spec['copies'], prebuild, mac_bundle_depends)

    if 'sources' in spec and self.flavor == 'win':
      outputs += self._WriteWinIdlFiles(spec, prebuild)

    if self.xcode_settings and self.xcode_settings.IsIosFramework():
      self._WriteIOSFrameworkHeaders(spec, outputs, prebuild)

    stamp = self._WriteCollapsedDependencies('actions_rules_copies', outputs)

    if self.is_mac_bundle:
      xcassets = self._WriteMacBundleResources(extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends)
      partial_info_plist = self._WriteMacXCAssets(xcassets, mac_bundle_depends)
      self._WriteMacInfoPlist(partial_info_plist, mac_bundle_depends)

    return stamp

  def _GenerateDescription(self, verb, message, fallback):
    """Generate and return a description of a build step.

    |verb| is the short summary, e.g. ACTION or RULE.
    |message| is a hand-written description, or None if not available.
    |fallback| is the gyp-level name of the step, usable as a fallback.
    """
    if self.toolset != 'target':
      verb += '(%s)' % self.toolset
    if message:
      return '%s %s' % (verb, self._ExpandSpecial(message))
    else:
      return '%s %s: %s' % (verb, self.name, fallback)

  def _WriteActions(self, actions, extra_sources, prebuild, extra_mac_bundle_resources):
    # Actions cd into the base directory.
    env = self._GetToolchainEnv()
    all_outputs = []
    for action in actions:
      # First write out a rule for the action.
      name = '%s_%s' % (action['action_name'], self.hash_for_rules)
      description = self._GenerateDescription('ACTION', action.get('message', None), name)
      is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) if self.flavor == 'win' else False)
      args = action['action']
      depfile = action.get('depfile', None)
      if depfile:
        depfile = self._ExpandSpecial(depfile, self.base_to_build)
      pool = 'console' if int(action.get('ninja_use_console', 0)) else None
      rule_name, _ = self._WriteNewNinjaRule(name, args, description, is_cygwin, env, pool, depfile=depfile)

      inputs = [self._GypPathToNinja(i, env) for i in action['inputs']]
      if int(action.get('process_outputs_as_sources', False)):
        extra_sources += action['outputs']
      if int(action.get('process_outputs_as_mac_bundle_resources', False)):
        extra_mac_bundle_resources += action['outputs']
      outputs = [self._GypPathToNinja(o, env) for o in action['outputs']]

      # Then write out an edge using the rule.
      self.ninja.build(outputs, rule_name, inputs, order_only=prebuild)
      all_outputs += outputs

      self.ninja.newline()

    return all_outputs

  def _WriteRules(self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources):
    env = self._GetToolchainEnv()
    all_outputs = []
    for rule in rules:
      # Skip a rule with no action and no inputs.
      if 'action' not in rule and not rule.get('rule_sources', []):
        continue

      # First write out a rule for the rule action.
      name = '%s_%s' % (rule['rule_name'], self.hash_for_rules)

      args = rule['action']
      description = self._GenerateDescription('RULE', rule.get('message', None), ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name)
      is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) if self.flavor == 'win' else False)
      pool = 'console' if int(rule.get('ninja_use_console', 0)) else None
      rule_name, args = self._WriteNewNinjaRule(name, args, description, is_cygwin, env, pool)

      # TODO: if the command references the outputs directly, we should
      # simplify it to just use $out.

      # Rules can potentially make use of some special variables which
      # must vary per source file.
      # Compute the list of variables we'll need to provide.
      special_locals = ('source', 'root', 'dirname', 'ext', 'name')
      needed_variables = {'source'}
      for argument in args:
        for var in special_locals:
          if '${%s}' % var in argument:
            needed_variables.add(var)
      needed_variables = sorted(needed_variables)

      def cygwin_mung(path):
        if is_cygwin:
          return path.replace('\\', '/')
        return path

      inputs = [self._GypPathToNinja(i, env) for i in rule.get('inputs', [])]

      # If there are n source files matching the rule, and m additional rule
      # inputs, then adding 'inputs' to each build edge written below will
      # write m * n inputs. Collapsing reduces this to m + n.
      sources = rule.get('rule_sources', [])
      num_inputs = len(inputs)
      if prebuild:
        num_inputs += 1
      if num_inputs > 2 and len(sources) > 2:
        inputs = [self._WriteCollapsedDependencies(rule['rule_name'], inputs, order_only=prebuild)]
        prebuild = []

      # For each source file, write an edge that generates all the outputs.
      for source in sources:
        source = os.path.normpath(source)
        dirname, basename = os.path.split(source)
        root, ext = os.path.splitext(basename)

        # Gather the list of inputs and outputs, expanding $vars if possible.
        outputs = [self._ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule['outputs']]

        if int(rule.get('process_outputs_as_sources', False)):
          extra_sources += outputs

        was_mac_bundle_resource = source in mac_bundle_resources
        if was_mac_bundle_resource or int(rule.get('process_outputs_as_mac_bundle_resources', False)):
          extra_mac_bundle_resources += outputs
          # Note: This is n_resources * n_outputs_in_rule.  Put to-be-removed
          # items in a set and remove them all in a single pass if this becomes
          # a performance issue.
          if was_mac_bundle_resource:
            mac_bundle_resources.remove(source)

        extra_bindings = []
        for var in needed_variables:
          if var == 'root':
            extra_bindings.append(('root', cygwin_mung(root)))
          elif var == 'dirname':
            # '$dirname' is a parameter to the rule action, which means
            # it shouldn't be converted to a Ninja path.  But we don't
            # want $!PRODUCT_DIR in there either.
            dirname_expanded = self._ExpandSpecial(dirname, self.base_to_build)
            extra_bindings.append(('dirname', cygwin_mung(dirname_expanded)))
          elif var == 'source':
            # '$source' is a parameter to the rule action, which means
            # it shouldn't be converted to a Ninja path.  But we don't
            # want $!PRODUCT_DIR in there either.
            source_expanded = self._ExpandSpecial(source, self.base_to_build)
            extra_bindings.append(('source', cygwin_mung(source_expanded)))
          elif var == 'ext':
            extra_bindings.append(('ext', ext))
          elif var == 'name':
            extra_bindings.append(('name', cygwin_mung(basename)))
          else:
            assert var is None, repr(var)

        outputs = [self._GypPathToNinja(o, env) for o in outputs]
        if self.flavor == 'win':
          # _WriteNewNinjaRule uses unique_name for creating an rsp file on win.
          extra_bindings.append(('unique_name', hashlib.md5(outputs[0].encode('utf-8')).hexdigest()))

        self.ninja.build(outputs, rule_name, self._GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings)

        all_outputs.extend(outputs)

    return all_outputs

  def _WriteCopies(self, copies, prebuild, mac_bundle_depends):
    outputs = []
    if self.xcode_settings:
      extra_env = self.xcode_settings.GetPerTargetSettings()
      env = self._GetToolchainEnv(additional_settings=extra_env)
    else:
      env = self._GetToolchainEnv()
    for cpy in copies:
      for path in cpy['files']:
        # Normalize the path so trailing slashes don't confuse us.
        path = os.path.normpath(path)
        basename = os.path.split(path)[1]
        src = self._GypPathToNinja(path, env)
        dst = self._GypPathToNinja(os.path.join(cpy['destination'], basename), env)
        outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild)
        if self.is_mac_bundle:
          # gyp has mac_bundle_resources to copy things into a bundle's
          # Resources folder, but there's no built-in way to copy files to other
          # places in the bundle. Hence, some targets use copies for this. Check
          # if this file is copied into the current bundle, and if so add it to
          # the bundle depends so that dependent targets get rebuilt if the copy
          # input changes.
          if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()):
            mac_bundle_depends.append(dst)

    return outputs

  def _WriteIOSFrameworkHeaders(self, spec, outputs, prebuild):
    """Prebuild steps to generate hmap files and copy headers to destination."""
    framework = self._ComputeMacBundleOutput()
    all_sources = spec['sources']
    copy_headers = spec['mac_framework_headers']
    output = self._GypPathToUniqueOutput('headers.hmap')
    self.xcode_settings.header_map_path = output
    all_headers = map(self._GypPathToNinja, filter(lambda x: x.endswith('.h'), all_sources))
    variables = [('framework', framework), ('copy_headers', map(self._GypPathToNinja, copy_headers))]
    outputs.extend(self.ninja.build(output, 'compile_ios_framework_headers', all_headers, variables=variables, order_only=prebuild))

  def _WriteMacBundleResources(self, resources, bundle_depends):
    """Writes ninja edges for 'mac_bundle_resources'."""
    xcassets = []

    extra_env = self.xcode_settings.GetPerTargetSettings()
    env = self._GetSortedXcodeEnv(additional_settings=extra_env)
    env = self._ComputeExportEnvString(env)
    isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)

    for output, res in gyp.xcode_emulation.GetMacBundleResources(generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self._GypPathToNinja, resources)):
      output = self._ExpandSpecial(output)
      if os.path.splitext(output)[-1] != '.xcassets':
        self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource'), ('env', env), ('binary', isBinary)])
        bundle_depends.append(output)
      else:
        xcassets.append(res)
    return xcassets

  def _WriteMacXCAssets(self, xcassets, bundle_depends):
    """Writes ninja edges for 'mac_bundle_resources' .xcassets files.

    This add an invocation of 'actool' via the 'mac_tool.py' helper script.
    It assumes that the assets catalogs define at least one image-set and
    thus an Assets.car file will be generated in the application resources
    directory. If this is not the case, then the build will probably be done
    at each invocation of ninja."""
    if not xcassets:
      return

    extra_arguments = {}
    settings_to_arg = {
        'XCASSETS_APP_ICON': 'app-icon',
        'XCASSETS_LAUNCH_IMAGE': 'launch-image',
    }
    settings = self.xcode_settings.xcode_settings[self.config_name]
    for settings_key, arg_name in settings_to_arg.items():
      value = settings.get(settings_key)
      if value:
        extra_arguments[arg_name] = value

    partial_info_plist = None
    if extra_arguments:
      partial_info_plist = self._GypPathToUniqueOutput('assetcatalog_generated_info.plist')
      extra_arguments['output-partial-info-plist'] = partial_info_plist

    outputs = [os.path.join(self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')]
    if partial_info_plist:
      outputs.append(partial_info_plist)

    keys = self._QuoteShellArgument(json.dumps(extra_arguments), self.flavor)
    extra_env = self.xcode_settings.GetPerTargetSettings()
    env = self._GetSortedXcodeEnv(additional_settings=extra_env)
    env = self._ComputeExportEnvString(env)

    bundle_depends.extend(self.ninja.build(outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)]))
    return partial_info_plist

  def _WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
    """Write build rules for bundle Info.plist files."""
    info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self._GypPathToNinja)
    if not info_plist:
      return
    out = self._ExpandSpecial(out)
    if defines:
      # Create an intermediate file to store preprocessed results.
      intermediate_plist = self._GypPathToUniqueOutput(os.path.basename(info_plist))
      defines = ' '.join([self._Define(d, self.flavor) for d in defines])
      info_plist = self.ninja.build(intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines', defines)])

    env = self._GetSortedXcodeEnv(additional_settings=extra_env)
    env = self._ComputeExportEnvString(env)

    if partial_info_plist:
      intermediate_plist = self._GypPathToUniqueOutput('merged_info.plist')
      info_plist = self.ninja.build(intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist])

    keys = self.xcode_settings.GetExtraPlistItems(self.config_name)
    keys = self._QuoteShellArgument(json.dumps(keys), self.flavor)
    isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
    self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)])
    bundle_depends.append(out)

  def _WriteSources(self, config_name, config, sources, pre_depends, precompiled_header, spec):
    """Write build rules to compile all of |sources|."""
    if self.toolset == 'host':
      self.ninja.variable('ar', '$ar_host')
      self.ninja.variable('cc', '$cc_host')
      self.ninja.variable('cxx', '$cxx_host')
      self.ninja.variable('ld', '$ld_host')
      self.ninja.variable('ldxx', '$ldxx_host')
      self.ninja.variable('nm', '$nm_host')
      self.ninja.variable('readelf', '$readelf_host')

    if self.flavor != 'mac' or len(self.archs) == 1:
      return self._WriteSourcesForArch(self.ninja, config_name, config, sources, pre_depends, precompiled_header, spec)
    else:
      return OrderedDict(
        (arch, self._WriteSourcesForArch(self.arch_subninjas[arch], config_name, config, sources, pre_depends, precompiled_header, spec, arch=arch))
        for arch in self.archs
      )

  def _WriteSourcesForArch(self, ninja_file, config_name, config, sources, pre_depends, precompiled_header, spec, arch=None):
    """Write build rules to compile all of |sources|."""

    extra_defines = []
    asmflags = ''
    cflags_objc = ''
    cflags_objcc = ''
    if self.flavor == 'mac':
      cflags = self.xcode_settings.GetCflags(config_name, arch=arch)
      cflags_c = self.xcode_settings.GetCflagsC(config_name)
      cflags_cc = self.xcode_settings.GetCflagsCC(config_name)
      cflags_objc = ['$cflags_c'] + self.xcode_settings.GetCflagsObjC(config_name)
      cflags_objcc = ['$cflags_cc'] + self.xcode_settings.GetCflagsObjCC(config_name)
    elif self.flavor == 'win':
      asmflags = self.msvs_settings.GetAsmflags(config_name)
      cflags = self.msvs_settings.GetCflags(config_name)
      cflags_c = self.msvs_settings.GetCflagsC(config_name)
      cflags_cc = self.msvs_settings.GetCflagsCC(config_name)
      extra_defines = self.msvs_settings.GetComputedDefines(config_name)
      # See comment at cc_command for why there's two .pdb files.
      pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName(config_name, self._ExpandSpecial)
      if not pdbpath_c:
        obj = 'obj'
        if self.toolset != 'target':
          obj += '.' + self.toolset
        pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name))
        pdbpath_c = pdbpath + '.c.pdb'
        pdbpath_cc = pdbpath + '.cc.pdb'
      self._WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c])
      self._WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc])
      self._WriteVariableList(ninja_file, 'pchprefix', [self.name])
    else:
      cflags = config.get('cflags', [])
      cflags_c = config.get('cflags_c', [])
      cflags_cc = config.get('cflags_cc', [])

    # Respect environment variables related to build, but target-specific
    # flags can still override them.
    if self.toolset == 'target':
      cflags_c = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CFLAGS', '').split() + cflags_c)
      cflags_cc = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CXXFLAGS', '').split() + cflags_cc)
    elif self.toolset == 'host':
      cflags_c = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CFLAGS_host', '').split() + cflags_c)
      cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CXXFLAGS_host', '').split() + cflags_cc)

    defines = config.get('defines', []) + extra_defines
    self._WriteVariableList(ninja_file, 'defines', [self._Define(d, self.flavor) for d in defines])
    if self.flavor == 'win':
      self._WriteVariableList(ninja_file, 'asmflags', map(self._ExpandSpecial, asmflags))
      self._WriteVariableList(ninja_file, 'rcflags', [self._QuoteShellArgument(self._ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self._GypPathToNinja)])

    include_dirs = config.get('include_dirs', [])

    env = self._GetToolchainEnv()
    if self.flavor == 'win':
      include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name)
    self._WriteVariableList(ninja_file, 'includes', [self._QuoteShellArgument('-I' + self._GypPathToNinja(i, env), self.flavor) for i in include_dirs])

    if self.flavor == 'win':
      midl_include_dirs = config.get('midl_include_dirs', [])
      midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs(midl_include_dirs, config_name)
      self._WriteVariableList(ninja_file, 'midl_includes', [self._QuoteShellArgument('-I' + self._GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs])

    pch_commands = precompiled_header.GetPchBuildCommands(arch)
    if self.flavor == 'mac':
      # Most targets use no precompiled headers, so only write these if needed.
      for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'), ('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]:
        include = precompiled_header.GetInclude(ext, arch)
        if include:
          ninja_file.variable(var, include)

    arflags = config.get('arflags', [])

    self._WriteVariableList(ninja_file, 'cflags', map(self._ExpandSpecial, cflags))
    self._WriteVariableList(ninja_file, 'cflags_c', map(self._ExpandSpecial, cflags_c))
    self._WriteVariableList(ninja_file, 'cflags_cc', map(self._ExpandSpecial, cflags_cc))
    if self.flavor == 'mac':
      self._WriteVariableList(ninja_file, 'cflags_objc', map(self._ExpandSpecial, cflags_objc))
      self._WriteVariableList(ninja_file, 'cflags_objcc', map(self._ExpandSpecial, cflags_objcc))
    self._WriteVariableList(ninja_file, 'arflags', map(self._ExpandSpecial, arflags))
    ninja_file.newline()
    outputs = []
    has_rc_source = False
    for source in sources:
      filename, ext = os.path.splitext(source)
      ext = ext[1:]
      obj_ext = self.obj_ext
      if ext in ('cc', 'cpp', 'cxx'):
        command = 'cxx'
        self.target.uses_cpp = True
      elif ext == 'c' or (ext == 'S' and self.flavor != 'win'):
        command = 'cc'
      elif ext == 's' and self.flavor != 'win':  # Doesn't generate .o.d files.
        command = 'cc_s'
      elif self.flavor == 'win' and ext == 'asm' and not self.msvs_settings.HasExplicitAsmRules(spec):
        command = 'asm'
        # Add the _asm suffix as msvs is capable of handling .cc and
        # .asm files of the same name without collision.
        obj_ext = '_asm.obj'
      elif self.flavor == 'mac' and ext == 'm':
        command = 'objc'
      elif self.flavor == 'mac' and ext == 'mm':
        command = 'objcxx'
        self.target.uses_cpp = True
      elif self.flavor == 'win' and ext == 'rc':
        command = 'rc'
        obj_ext = '.res'
        has_rc_source = True
      else:
        # Ignore unhandled extensions.
        continue
      inpt = self._GypPathToNinja(source)
      otpt = self._GypPathToUniqueOutput(filename + obj_ext)
      if arch is not None:
        otpt = self._AddArch(otpt, arch)
      implicit = precompiled_header.GetObjDependencies([inpt], [otpt], arch)
      variables = []
      if self.flavor == 'win':
        variables, otpt, implicit = precompiled_header.GetFlagsModifications(inpt, otpt, implicit, command, cflags_c, cflags_cc, self._ExpandSpecial)
      ninja_file.build(otpt, command, inpt, implicit=[gch for _, _, gch in implicit], order_only=pre_depends, variables=variables)
      outputs.append(otpt)

    if has_rc_source:
      resource_include_dirs = config.get('resource_include_dirs', include_dirs)
      self._WriteVariableList(ninja_file, 'resource_includes', [self._QuoteShellArgument('-I' + self._GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs])

    self._WritePchTargets(ninja_file, pch_commands)

    ninja_file.newline()
    return outputs

  @staticmethod
  def _WritePchTargets(ninja_file, pch_commands):
    """Writes ninja rules to compile prefix headers."""
    if not pch_commands:
      return

    for gch, lang_flag, lang, inpt in pch_commands:
      var_name = {
        'c': 'cflags_pch_c',
        'cc': 'cflags_pch_cc',
        'm': 'cflags_pch_objc',
        'mm': 'cflags_pch_objcc',
      }[lang]

      lang_map = {'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', }
      cmd = lang_map.get(lang)
      ninja_file.build(gch, cmd, inpt, variables=[(var_name, lang_flag)])

  def _WriteLink(self, spec, config_name, config, link_deps, compile_deps):
    """Write out a link step. Fills out target.binary. """
    if self.flavor != 'mac' or len(self.archs) == 1:
      return self._WriteLinkForArch(self.ninja, spec, config_name, config, link_deps, compile_deps)
    else:
      output = self._ComputeOutput(spec)
      inputs = [self._WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], compile_deps, arch=arch) for arch in self.archs]
      extra_bindings = []
      build_output = output
      if not self.is_mac_bundle:
        self._AppendPostbuildVariable(extra_bindings, spec, output, output)

      # TODO(yyanagisawa): more work needed to fix:
      # https://code.google.com/p/gyp/issues/detail?id=411
      if spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle:
        extra_bindings.append(('lib', output))
        self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings)
      else:
        self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings)
      return output

  def _WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None):
    """Write out a link step. Fills out target.binary. """
    command = {
      'executable':      'link',
      'loadable_module': 'solink_module',
      'shared_library':  'solink',
    }[spec['type']]
    command_suffix = ''

    implicit_deps = set()
    solibs = set()
    order_deps = set()

    if compile_deps:
      # Normally, the compiles of the target already depend on compile_deps,
      # but a shared_library target might have no sources and only link together
      # a few static_library deps, so the link step also needs to depend
      # on compile_deps to make sure actions in the shared_library target
      # get run before the link.
      order_deps.add(compile_deps)

    if 'dependencies' in spec:
      # Two kinds of dependencies:
      # - Linkable dependencies (like a .a or a .so): add them to the link line.
      # - Non-linkable dependencies (like a rule that generates a file
      #   and writes a stamp file): add them to implicit_deps
      extra_link_deps = set()
      for dep in spec['dependencies']:
        target = self.target_outputs.get(dep)
        if not target:
          continue
        linkable = target.Linkable()
        if linkable:
          new_deps = []
          if self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name):
            new_deps = target.component_objs
            if target.compile_deps:
              order_deps.add(target.compile_deps)
          elif self.flavor == 'win' and target.import_lib:
            new_deps = [target.import_lib]
          elif target.UsesToc(self.flavor):
            solibs.add(target.binary)
            implicit_deps.add(target.binary + '.TOC')
          else:
            new_deps = [target.binary]
          for new_dep in new_deps:
            if new_dep not in extra_link_deps:
              extra_link_deps.add(new_dep)
              link_deps.append(new_dep)

        final_output = target.FinalOutput()
        if not linkable or final_output != target.binary:
          implicit_deps.add(final_output)

    extra_bindings = []
    if self.target.uses_cpp and self.flavor != 'win':
      extra_bindings.append(('ld', '$ldxx'))

    output = self._ComputeOutput(spec, arch)
    if arch is None and not self.is_mac_bundle:
      self._AppendPostbuildVariable(extra_bindings, spec, output, output)

    is_executable = spec['type'] == 'executable'
    # The ldflags config key is not used on mac or win. On those platforms
    # linker flags are set via xcode_settings and msvs_settings, respectively.
    if self.toolset == 'target':
      env_ldflags = os.environ.get('LDFLAGS', '').split()
    else: # self.toolset == 'host'
      env_ldflags = os.environ.get('LDFLAGS_host', '').split()
    if self.flavor == 'mac':
      ldflags = self.xcode_settings.GetLdflags(config_name, self._ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self._GypPathToNinja, arch)
      ldflags = env_ldflags + ldflags
    elif self.flavor == 'win':
      manifest_base_name = self._GypPathToUniqueOutput(self.ComputeOutputFileName(spec))
      ldflags, intermediate_manifest, manifest_files = self.msvs_settings.GetLdflags(config_name, self._GypPathToNinja, self._ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build)
      ldflags = env_ldflags + ldflags
      self._WriteVariableList(ninja_file, 'manifests', manifest_files)
      implicit_deps = implicit_deps.union(manifest_files)
      if intermediate_manifest:
        self._WriteVariableList(ninja_file, 'intermediatemanifest', [intermediate_manifest])
      command_suffix = GetWinLinkRuleNameSuffix(self.msvs_settings.IsEmbedManifest(config_name))
      def_file = self.msvs_settings.GetDefFile(self._GypPathToNinja)
      if def_file:
        implicit_deps.add(def_file)
    else:
      # Respect environment variables related to build, but target-specific
      # flags can still override them.
      ldflags = env_ldflags + config.get('ldflags', [])
      if is_executable and len(solibs):
        rpath = 'lib/'
        if self.toolset != 'target':
          rpath += self.toolset
          ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath)
        else:
          ldflags.append('-Wl,-rpath=%s' % self.target_rpath)
        ldflags.append('-Wl,-rpath-link=%s' % rpath)
    self._WriteVariableList(ninja_file, 'ldflags', map(self._ExpandSpecial, ldflags))

    library_dirs = config.get('library_dirs', [])
    if self.flavor == 'win':
      library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs]
      library_dirs = ['/LIBPATH:' + self._QuoteShellArgument(self._GypPathToNinja(l), self.flavor) for l in library_dirs]
    else:
      library_dirs = [self._QuoteShellArgument('-L' + self._GypPathToNinja(l), self.flavor) for l in library_dirs]

    libraries = gyp.common.uniquer(map(self._ExpandSpecial, spec.get('libraries', [])))
    if self.flavor == 'mac':
      libraries = self.xcode_settings.AdjustLibraries(libraries, config_name)
    elif self.flavor == 'win':
      libraries = self.msvs_settings.AdjustLibraries(libraries)

    self._WriteVariableList(ninja_file, 'libs', library_dirs + libraries)

    linked_binary = output

    if command in ('solink', 'solink_module'):
      extra_bindings.append(('soname', os.path.split(output)[1]))
      extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output)))
      if self.flavor != 'win':
        link_file_list = output
        if self.is_mac_bundle:
          # 'Dependency Framework.framework/Versions/A/Dependency Framework' ->
          # 'Dependency Framework.framework.rsp'
          link_file_list = self.xcode_settings.GetWrapperName()
        if arch:
          link_file_list += '.' + arch
        link_file_list += '.rsp'
        # If an rspfile contains spaces, ninja surrounds the filename with
        # quotes around it and then passes it to open(), creating a file with
        # quotes in its name (and when looking for the rsp file, the name
        # makes it through bash which strips the quotes) :-/
        link_file_list = link_file_list.replace(' ', '_')
        extra_bindings.append(('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list)))
      if self.flavor == 'win':
        extra_bindings.append(('binary', output))
        if '/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name):
          self.target.import_lib = output + '.lib'
          extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib))
          pdbname = self.msvs_settings.GetPDBName(config_name, self._ExpandSpecial, output + '.pdb')
          output = [output, self.target.import_lib]
          if pdbname:
            output.append(pdbname)
      elif not self.is_mac_bundle:
        output = [output, output + '.TOC']
      else:
        command = command + '_notoc'
    elif self.flavor == 'win':
      extra_bindings.append(('binary', output))
      pdbname = self.msvs_settings.GetPDBName(config_name, self._ExpandSpecial, output + '.pdb')
      if pdbname:
        output = [output, pdbname]

    if len(solibs):
      extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(sorted(solibs))))

    ninja_file.build(output, command + command_suffix, link_deps, implicit=sorted(implicit_deps), order_only=list(order_deps), variables=extra_bindings)
    return linked_binary

  def _WriteTarget(self, spec, config_name, config, link_deps, compile_deps):
    extra_link_deps = any(self.target_outputs.get(dep).Linkable() for dep in spec.get('dependencies', []) if dep in self.target_outputs)
    if spec['type'] == 'none' or (not link_deps and not extra_link_deps):
      # TODO(evan): don't call this function for 'none' target types, as
      # it doesn't do anything, and we fake out a 'binary' with a stamp file.
      self.target.binary = compile_deps
      self.target.type = 'none'
    elif spec['type'] == 'static_library':
      self.target.binary = self._ComputeOutput(spec)
      if self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library:
        self.ninja.build(self.target.binary, 'alink_thin', link_deps, order_only=compile_deps)
      else:
        variables = []
        if self.xcode_settings:
          libtool_flags = self.xcode_settings.GetLibtoolflags(config_name)
          if libtool_flags:
            variables.append(('libtool_flags', libtool_flags))
        if self.msvs_settings:
          libflags = self.msvs_settings.GetLibFlags(config_name, self._GypPathToNinja)
          variables.append(('libflags', libflags))

        if self.flavor != 'mac' or len(self.archs) == 1:
          self._AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary)
          self.ninja.build(self.target.binary, 'alink', link_deps, order_only=compile_deps, variables=variables)
        else:
          inputs = []
          for arch in self.archs:
            output = self._ComputeOutput(spec, arch)
            self.arch_subninjas[arch].build(output, 'alink', link_deps[arch], order_only=compile_deps, variables=variables)
            inputs.append(output)
          # TODO: It's not clear if libtool_flags should be passed to the alink
          # call that combines single-arch .a files into a fat .a file.
          self._AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary)
          self.ninja.build(self.target.binary, 'alink', inputs,
                           # FIXME: test proving order_only=compile_deps isn't needed.
                           variables=variables)
    else:
      self.target.binary = self._WriteLink(spec, config_name, config, link_deps, compile_deps)
    return self.target.binary

  def _WriteMacBundle(self, spec, mac_bundle_depends, is_empty):
    assert self.is_mac_bundle
    package_framework = spec['type'] in ('shared_library', 'loadable_module')
    output = self._ComputeMacBundleOutput()
    if is_empty:
      output += '.stamp'
    variables = []
    self._AppendPostbuildVariable(variables, spec, output, self.target.binary, is_command_start=not package_framework)
    if package_framework and not is_empty:
      if spec['type'] == 'shared_library' and self.xcode_settings.isIOS:
        self.ninja.build(output, 'package_ios_framework', mac_bundle_depends, variables=variables)
      else:
        variables.append(('version', self.xcode_settings.GetFrameworkVersion()))
        self.ninja.build(output, 'package_framework', mac_bundle_depends, variables=variables)
    else:
      self.ninja.build(output, 'stamp', mac_bundle_depends, variables=variables)
    self.target.bundle = output
    return output

  def _GetToolchainEnv(self, additional_settings=None):
    """Returns the variables toolchain would set for build steps."""
    env = self._GetSortedXcodeEnv(additional_settings=additional_settings)
    if self.flavor == 'win':
      env = self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name)
    return env

  def _GetSortedXcodeEnv(self, additional_settings=None):
    """Returns the variables Xcode would set for build steps."""
    assert self.abs_build_dir
    path = os.path.join(self.abs_build_dir, self.build_to_base)
    return gyp.xcode_emulation.GetSortedXcodeEnv(self.xcode_settings, self.abs_build_dir, path, self.config_name, additional_settings)

  def _GetSortedXcodePostbuildEnv(self):
    """Returns the variables Xcode would set for postbuild steps."""
    postbuild_settings = {}
    # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
    # TODO(thakis): It would be nice to have some general mechanism instead.
    strip_save_file = self.xcode_settings.GetPerTargetSetting('CHROMIUM_STRIP_SAVE_FILE')
    if strip_save_file:
      postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file
    return self._GetSortedXcodeEnv(additional_settings=postbuild_settings)

  def _AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False):
    """Adds a 'postbuild' variable if there is a postbuild for |output|."""
    postbuild = self._GetPostbuildCommand(spec, output, binary, is_command_start)
    if postbuild:
      variables.append(('postbuilds', postbuild))

  def _GetPostbuildCommand(self, spec, output, output_binary, is_command_start):
    """Returns a shell command that runs all the postbuilds, and removes
    |output| if any of them fails. If |is_command_start| is False, then the
    returned string will start with ' && '."""
    if not self.xcode_settings or spec['type'] == 'none' or not output:
      return ''
    output = self._QuoteShellArgument(output, self.flavor)
    postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True)
    if output_binary is not None:
      output_path = os.path.normpath(os.path.join(self.base_to_build, output))
      output_binary_path = self._QuoteShellArgument(os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor)
      postbuilds = self.xcode_settings.AddImplicitPostbuilds(self.config_name, output_path, output_binary_path, postbuilds, quiet=True)

    if not postbuilds:
      return ''
    # Postbuilds expect to be run in the gyp file's directory, so insert an
    # implicit postbuild to cd to there.
    postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.build_to_base]))
    env = self._ComputeExportEnvString(self._GetSortedXcodePostbuildEnv())
    # G will be non-null if any postbuild fails. Run all postbuilds in a
    # subshell.
    commands = env + ' (' + ' && '.join([ninja_syntax.escape(command) for command in postbuilds])
    command_string = (commands + '); G=$$?; '
                      # Remove the final output if any postbuild failed.
                      '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)')
    if is_command_start:
      return '(' + command_string + ' && '
    else:
      return '$ && (' + command_string

  @staticmethod
  def _ComputeExportEnvString(env):
    """Given an environment, returns a string looking like
        'export FOO=foo; export BAR="${FOO} bar;'
    that exports |env| to the shell."""
    export_str = []
    for k, v in env:
      export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v))))
    return ' '.join(export_str)

  def _ComputeMacBundleOutput(self):
    """Return the 'output' (full output path) to a bundle output directory."""
    assert self.is_mac_bundle
    path = generator_default_variables['PRODUCT_DIR']
    return self._ExpandSpecial(os.path.join(path, self.xcode_settings.GetWrapperName()))

  def _ComputeOutput(self, spec, arch=None):
    """Compute the path for the final output of the spec."""
    typ = spec['type']

    if self.flavor == 'win':
      override = self.msvs_settings.GetOutputName(self.config_name, self._ExpandSpecial)
      if override:
        return override

    if arch is None and self.flavor == 'mac' and typ in (
        'static_library', 'executable', 'shared_library', 'loadable_module'):
      filename = self.xcode_settings.GetExecutablePath()
    else:
      filename = self.ComputeOutputFileName(spec, typ)

    if arch is None and 'product_dir' in spec:
      path = os.path.join(spec['product_dir'], filename)
      return self._ExpandSpecial(path)

    # Some products go into the output root, libraries go into shared library
    # dir, and everything else goes into the normal place.
    type_in_output_root = ['executable', 'loadable_module']
    if self.flavor == 'mac' and self.toolset == 'target':
      type_in_output_root += ['shared_library', 'static_library']
    elif self.flavor == 'win' and self.toolset == 'target':
      type_in_output_root += ['shared_library']

    if arch is not None:
      # Make sure partial executables don't end up in a bundle or the regular
      # output directory.
      archdir = 'arch'
      if self.toolset != 'target':
        archdir = os.path.join('arch', '%s' % self.toolset)
      return os.path.join(archdir, self._AddArch(filename, arch))
    elif typ in type_in_output_root or self.is_standalone_static_library:
      return filename
    elif typ == 'shared_library':
      libdir = 'lib'
      if self.toolset != 'target':
        libdir = os.path.join('lib', '%s' % self.toolset)
      return os.path.join(libdir, filename)
    else:
      return self._GypPathToUniqueOutput(filename, qualified=False)

  @staticmethod
  def _WriteVariableList(ninja_file, var, values):
    assert not isinstance(values, str)
    if values is None:
      values = []
    ninja_file.variable(var, ' '.join(values))

  def _WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool, depfile=None):
    """Write out a new ninja "rule" statement for a given command.

    Returns the name of the new rule, and a copy of |args| with variables
    expanded."""

    if self.flavor == 'win':
      args = [self.msvs_settings.ConvertVSMacros(arg, self.base_to_build, config=self.config_name) for arg in args]
      description = self.msvs_settings.ConvertVSMacros(description, config=self.config_name)
    elif self.flavor == 'mac':
      # |env| is an empty list on non-mac.
      args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args]
      description = gyp.xcode_emulation.ExpandEnvVars(description, env)

    # TODO: we shouldn't need to qualify names; we do it because
    # currently the ninja rule namespace is global, but it really
    # should be scoped to the subninja.
    rule_name = self.name
    if self.toolset == 'target':
      rule_name += '.' + self.toolset
    rule_name += '.' + name
    rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name)

    # Remove variable references, but not if they refer to the magic rule
    # variables.  This is not quite right, as it also protects these for
    # actions, not just for rules where they are valid. Good enough.
    protect = ['${root}', '${dirname}', '${source}', '${ext}', '${name}']
    protect = '(?!' + '|'.join(map(re.escape, protect)) + ')'
    description = re.sub(protect + r'\$', '_', description)

    # gyp dictates that commands are run from the base directory.
    # cd into the directory before running, and adjust paths in
    # the arguments to point to the proper locations.
    rspfile = None
    rspfile_content = None
    args = [self._ExpandSpecial(arg, self.base_to_build) for arg in args]
    if self.flavor == 'win':
      rspfile = rule_name + '.$unique_name.rsp'
      # The cygwin case handles this inside the bash sub-shell.
      run_in = '' if is_cygwin else ' ' + self.build_to_base
      if is_cygwin:
        rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine(args, self.build_to_base)
      else:
        rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args)
      command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in)
    else:
      env = self._ComputeExportEnvString(env)
      command = gyp.common.EncodePOSIXShellList(args)
      command = 'cd %s; ' % self.build_to_base + env + command

    # GYP rules/actions express being no-ops by not touching their outputs.
    # Avoid executing downstream dependencies in this case by specifying
    # restat=1 to ninja.
    self.ninja.rule(rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content)
    self.ninja.newline()

    return rule_name, args

  def ComputeOutputFileName(self, spec, typ=None):
    """Compute the filename of the final output for the current target."""
    if not typ:
      typ = spec['type']

    default_variables = copy.copy(generator_default_variables)
    CalculateVariables(default_variables, {'flavor': self.flavor})

    # Compute filename prefix: the product prefix, or a default for
    # the product type.
    DEFAULT_PREFIX = {
      'loadable_module': default_variables['SHARED_LIB_PREFIX'],
      'shared_library': default_variables['SHARED_LIB_PREFIX'],
      'static_library': default_variables['STATIC_LIB_PREFIX'],
      'executable': default_variables['EXECUTABLE_PREFIX'],
    }
    prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(typ, ''))

    # Compute filename extension: the product extension, or a default
    # for the product type.
    DEFAULT_EXTENSION = {
      'loadable_module': default_variables['SHARED_LIB_SUFFIX'],
      'shared_library': default_variables['SHARED_LIB_SUFFIX'],
      'static_library': default_variables['STATIC_LIB_SUFFIX'],
      'executable': default_variables['EXECUTABLE_SUFFIX'],
    }
    extension = spec.get('product_extension')
    if extension:
      extension = '.' + extension
    else:
      extension = DEFAULT_EXTENSION.get(typ, '')

    if 'product_name' in spec:
      # If we were given an explicit name, use that.
      target = spec['product_name']
    else:
      # Otherwise, derive a name from the target name.
      target = spec['target_name']
      if prefix == 'lib':
        # Snip out an extra 'lib' from libs if appropriate.
        target = self._StripPrefix(target, 'lib')

    if typ in ('static_library', 'loadable_module', 'shared_library', 'executable'):
      return '%s%s%s' % (prefix, target, extension)
    elif typ == 'none':
      return '%s.stamp' % target
    else:
      raise Exception('Unhandled output type %s' % typ)

  def WriteSpec(self):
    """
    The entry point for NinjaWriter: write the build rules for a spec.

    Returns a Target object, which represents the output paths for this spec.
    Returns None if there are no outputs (e.g. a settings-only 'none' type
    target).
    """

    if self.flavor == 'mac':
      self.xcode_settings = xcode_emulation.XcodeSettings(self.spec)
      mac_toolchain_dir = self.generator_flags.get('mac_toolchain_dir', None)
      if mac_toolchain_dir:
        self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir

    if self.flavor == 'win':
      self.msvs_settings = msvs_emulation.MsvsSettings(self.spec, self.generator_flags)
      arch = self.msvs_settings.GetArch(self.config_name)
      self.ninja.variable('arch', self.win_env[arch])
      self.ninja.variable('cc', '$cl_' + arch)
      self.ninja.variable('cxx', '$cl_' + arch)
      self.ninja.variable('cc_host', '$cl_' + arch)
      self.ninja.variable('cxx_host', '$cl_' + arch)
      self.ninja.variable('asm', '$ml_' + arch)

    if self.flavor == 'mac':
      self.archs = self.xcode_settings.GetActiveArchs(self.config_name)
      if len(self.archs) > 1:
        self.arch_subninjas = dict(
          (arch, ninja_syntax.Writer(OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)))))
          for arch in self.archs
        )

    # Compute pre-depends for all rules.
    # actions_depends is the dependencies this target depends on before running any of its action/rule/copy steps.
    # compile_depends is the dependencies this target depends on before running any of its compile steps.
    actions_depends = []
    compile_depends = []
    # TODO(evan): it is rather confusing which things are lists and which
    # are strings.  Fix these.
    if 'dependencies' in self.spec:
      for dep in self.spec['dependencies']:
        if dep in self.target_outputs:
          target = self.target_outputs[dep]
          actions_depends.append(target.PreActionInput(self.flavor))
          compile_depends.append(target.PreCompileInput())
          if target.uses_cpp:
            self.target.uses_cpp = True
      actions_depends = [d for d in actions_depends if d]
      compile_depends = [d for d in compile_depends if d]
      actions_depends = self._WriteCollapsedDependencies('actions_depends', actions_depends)
      compile_depends = self._WriteCollapsedDependencies('compile_depends', compile_depends)
      self.target.preaction_stamp = actions_depends
      self.target.precompile_stamp = compile_depends

    # Write out actions, rules, and copies.  These must happen before we
    # compile any sources, so compute a list of predependencies for sources
    # while we do it.
    extra_sources = []
    mac_bundle_depends = []
    self.target.actions_stamp = self._WriteActionsRulesCopies(self.spec, extra_sources, actions_depends, mac_bundle_depends)

    # If we have actions/rules/copies, we depend directly on those, but
    # otherwise we depend on dependent target's actions/rules/copies etc.
    # We never need to explicitly depend on previous target's link steps,
    # because no compile ever depends on them.
    compile_depends_stamp = self.target.actions_stamp or compile_depends

    # Write out the compilation steps, if any.
    link_deps = []
    try:
      sources = extra_sources + self.spec.get('sources', [])
    except TypeError:
      print('extra_sources: ', str(extra_sources))
      print('spec.get("sources"): ', str(self.spec.get('sources')))
      raise
    if sources:
      if self.flavor == 'mac' and len(self.archs) > 1:
        # Write subninja file containing compile and link commands scoped to
        # a single arch if a fat binary is being built.
        for arch in self.archs:
          self.ninja.subninja(self._SubninjaNameForArch(arch))

      if self.flavor == 'win':
        gyp.msvs_emulation.VerifyMissingSources(sources, self.abs_build_dir, self.generator_flags, self._GypPathToNinja)
        pch = gyp.msvs_emulation.PrecompiledHeader(self.msvs_settings, self.config_name, self._GypPathToNinja, self._GypPathToUniqueOutput, self.obj_ext)
      else:
        pch = gyp.xcode_emulation.MacPrefixHeader(self.xcode_settings, self._GypPathToNinja, lambda path, lang: self._GypPathToUniqueOutput(path + '-' + lang))
      link_deps = self._WriteSources(self.config_name, self.config, sources, compile_depends_stamp, pch, self.spec)
      # Some actions/rules output 'sources' that are already object files.
      obj_outputs = [f for f in sources if f.endswith(self.obj_ext)]
      if obj_outputs:
        if self.flavor != 'mac' or len(self.archs) == 1:
          link_deps += [self._GypPathToNinja(o) for o in obj_outputs]
        else:
          print("Warning: Actions/rules writing object files don't work with multi-arch targets, dropping. (target %s)" % self.spec['target_name'])
    elif self.flavor == 'mac' and len(self.archs) > 1:
      link_deps = OrderedDict((a, []) for a in self.archs)

    compile_deps = self.target.actions_stamp or actions_depends
    if self.flavor == 'win' and self.target.type == 'static_library':
      self.target.component_objs = link_deps
      self.target.compile_deps = compile_deps

    # Write out a link step, if needed.
    output = None
    is_empty_bundle = not link_deps and not mac_bundle_depends
    if link_deps or self.target.actions_stamp or actions_depends:
      output = self._WriteTarget(self.spec, self.config_name, self.config, link_deps, compile_deps)
      if self.is_mac_bundle:
        mac_bundle_depends.append(output)

    # Bundle all of the above together, if needed.
    if self.is_mac_bundle:
      output = self._WriteMacBundle(self.spec, mac_bundle_depends, is_empty_bundle)

    if not output:
      return None

    assert self.target.FinalOutput(), output
    return self.target


  def _Define(self, d, flavor):
    """Takes a preprocessor define and returns a -D parameter that's ninja- and
    shell-escaped."""
    if flavor == 'win':
      # cl.exe replaces literal # characters with = in preprocesor definitions for
      # some reason. Octal-encode to work around that.
      d = d.replace('#', '\\%03o' % ord('#'))
    return self._QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)


  @staticmethod
  def _StripPrefix(arg, prefix):
    if arg.startswith(prefix):
      return arg[len(prefix):]
    return arg


  @staticmethod
  def _QuoteShellArgument(arg, flavor):
    """Quote a string such that it will be interpreted as a single argument
    by the shell."""
    # Rather than attempting to enumerate the bad shell characters, just
    # whitelist common OK ones and quote anything else.
    if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg):
      return arg  # No quoting necessary.
    if flavor == 'win':
      return gyp.msvs_emulation.QuoteForRspFile(arg)
    return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"


  @staticmethod
  def _AddArch(output, arch):
    """Adds an arch string to an output path."""
    output, extension = os.path.splitext(output)
    return '%s.%s%s' % (output, arch, extension)
